import React from 'react';
import './page1.css'

// useSelector：用于获取状态
// useDispatch：用于操作全局状态
import {useDispatch, useSelector} from 'react-redux'
// createAction：用来帮我们创建action
import { createAction } from '@reduxjs/toolkit'
// 导入创建好的action对象
// import { setSchoolName,setSchoolAddress,setSchool } from "../../store/modules/school";
// 导入school切片对象
import schoolSlice from "../../store/modules/school";

function Son1(){
    // 定义一个派发器，用于更新状态
    const dispatch = useDispatch()
    const  stu  = useSelector(state => state.stu)
    const { obj } = useSelector(state => state.school)
    // 使用createAction方法，生成action
    let setStuName = createAction('setStuName')
    let setStu = createAction('setStu')
    // 从school切片对象的actions中获取指定的action
    let { setSchoolName,setSchoolAddress,setSchool,setObj } = schoolSlice.actions
    return (
        <div className="son1">
            <button onClick={()=>{dispatch(setStuName('李四'))}}>修改姓名1</button>
            <button onClick={()=>{dispatch(setStu( {...stu,name:'王五'} ))}}>修改姓名2</button>
            <button onClick={()=>{dispatch({type:'setStuAge',payload:25})}} >修改年龄1</button>
            <button onClick={()=>{dispatch({type:'setStu',payload:{...stu,age:12}})}}>修改年龄2</button>
            <button onClick={()=>{dispatch({type:'setStuSex',payload:'女'})}} >修改性别1</button>
            <button onClick={()=>{dispatch({type:'setStu',payload:{...stu,sex:'未知'}})}}>修改性别2</button>
            <span> | </span>
            <button onClick={()=>{dispatch(setSchoolName('成都职业技术学院'))}}>修改学校名称</button>
            <button onClick={()=>{dispatch(setSchoolAddress('成都帝豪别墅'))}}>修改学校地址</button>
            <button onClick={()=>{dispatch(setSchool({name:'全部修改名称'}))}}>修改对象</button>
            <button onClick={()=>{dispatch(setObj({id:'123'}))}}>设置id</button>
            <button onClick={()=>{dispatch(setObj({title:'标题'}))}}>设置title</button>
        </div>
    )
}

function Page1(props) {
    // 获取redux中定义的全局状态
    const {stu,school} = useSelector(state => state)
    return (
        <div className='page'>
            <p>姓名：{stu.name}</p>
            <p>年龄：{stu.age}</p>
            <p>性别：{stu.sex}</p>
            <hr/>
            <p>学校姓名：{school.name}</p>
            <p>学校地址：{school.address}</p>
            <hr/>
            <p>id：{school.obj.id}</p>
            <p>title：{school.obj.title}</p>
            <Son1></Son1>
        </div>
    );
}

export default Page1;
